package org.adorsys.aderp.aderplogin.security.endpoint;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.adorsys.aderp.aderplogin.client.basic.ClientBasicAuthenticator;
import org.adorsys.aderp.aderplogin.client.common.Oauth2User;
import org.adorsys.aderp.aderplogin.security.LocalUserDetailServiceImpl;
import org.adorsys.aderp.aderplogin.security.token.Oauth2TokenReplicationService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Return a schrinked version of user data, consisting of the
 * the user key and the selected roles applicable to the requesting
 * client.
 * 
 * This information can be used by any client to build a user details object.
 * 
 * @author Dave Syer
 * 
 */
@Controller
public class UserEndpoint extends AbstractEndpoint {
	
	@Resource
	Oauth2TokenReplicationService oauth2TokenReplicationService;
	
	@Resource
	LocalUserDetailServiceImpl localUserDetailServiceImpl;
	
	@Resource
	private ClientBasicAuthenticator clientBasicAuthenticator;

	@RequestMapping(value = "/oauth/user")
	public ResponseEntity<Oauth2User> getOauth2User(@RequestParam("token") String token,
			@RequestParam Map<String, String> parameters, @RequestHeader HttpHeaders headers, HttpServletRequest request) {

		UsernamePasswordAuthenticationToken client = clientBasicAuthenticator.authenticate(request);
		if (client==null || !client.isAuthenticated()) {
			throw new InsufficientAuthenticationException("The client is not authenticated.");
		}

		String clientId = client.getName();

//		Set<String> scope = OAuth2Utils.parseScope(parameters.get("scope"));
		// TODO make sure scope is trust.

		Oauth2User loadUser = oauth2TokenReplicationService.loadUser(token, clientId);
		return getResponse(loadUser);

	}

	private ResponseEntity<Oauth2User> getResponse(Oauth2User oauth2User) {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Cache-Control", "no-store");
		headers.setContentType(MediaType.APPLICATION_JSON);
		return new ResponseEntity<Oauth2User>(oauth2User, headers, HttpStatus.OK);
	}
}
